//
//  DRFriendsFoodPairingVC.m
//  DoctorRen
//
//  Created by 范伟健 on 2019/1/18.
//

#import "DRFriendsFoodPairingVC.h"
#import "DRFriendsFoodCell.h"
#import <Masonry/Masonry.h>
#import "DRFoodPairingFooterView.h"
#import "DRFoodPairingDataModel.h"

@interface DRFriendsFoodPairingVC ()<UITableViewDelegate, UITableViewDataSource ,DRFoodPairingFooterViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong , nonatomic) UIButton *lunchButton;

@property (nonatomic, strong) UIButton *dinnerButton;

@property (nonatomic, strong) UILabel *describeLabel;

@property (nonatomic, assign) BOOL showLunch;// 是否显示午餐

@property (nonatomic, strong) UILabel *addedLabel;

@property (nonatomic, strong) UILabel *canAddLabel;

@property (nonatomic, strong) DRFamilyFoodPairingModel *model;

@property (nonatomic, strong) UILabel *tipLabel;

@property (nonatomic, copy) void(^errorBlock)(NSError *);

@end

@implementation DRFriendsFoodPairingVC

- (UIButton *)lunchButton{
    if (!_lunchButton) {
        _lunchButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_lunchButton setTitle:@"午餐" forState:(UIControlStateNormal)];
        [_lunchButton setBackgroundColor:There_Green];
        _lunchButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [_lunchButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    }
    return _lunchButton;
}

-(UIButton *)dinnerButton{
    if (!_dinnerButton) {
        _dinnerButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _dinnerButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [_dinnerButton setTitle:@"晚餐" forState:(UIControlStateNormal)];
        [_dinnerButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    }
    return _dinnerButton;
}

-(UILabel *)describeLabel{
    if (!_describeLabel) {
        _describeLabel = [[UILabel alloc] init];
        _describeLabel.font = [UIFont systemFontOfSize:13];
        _describeLabel.textColor = Text_Gray;
        _describeLabel.numberOfLines = 0;
        _describeLabel.text = @"该餐总能量1000千卡，已超200卡";
    }
    return _describeLabel;
}

-(UILabel *)addedLabel{
    if (!_addedLabel) {
        _addedLabel = [[UILabel alloc] init];
        _addedLabel.textColor = [UIColor blackColor];
        _addedLabel.font = [UIFont systemFontOfSize:18];
    }
    return _addedLabel;
}

-(UILabel *)canAddLabel{
    if (!_canAddLabel) {
        _canAddLabel = [[UILabel alloc] init];
        _canAddLabel.textColor = [UIColor blackColor];
        _canAddLabel.font = [UIFont systemFontOfSize:18];
    }
    return _canAddLabel;
}


-(UIView *)tableHeaderView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, 110);
    [view addSubview:self.lunchButton];
    [self.lunchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(56);
        make.height.mas_equalTo(28);
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(20);
    }];
    self.lunchButton.layer.cornerRadius = 14;
    self.lunchButton.layer.masksToBounds = YES;
    
    [view addSubview:self.dinnerButton];
    [self.dinnerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(56);
        make.height.mas_equalTo(28);
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(self.lunchButton.mas_right).mas_offset(20);
    }];
    self.dinnerButton.layer.cornerRadius = 14;
    self.dinnerButton.layer.masksToBounds = YES;
    
    [view addSubview:self.describeLabel];
    [self.describeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.lunchButton.mas_bottom).mas_offset(10);
        make.left.mas_equalTo(self.lunchButton);
        make.right.mas_equalTo(-20);
    }];
    return view;
}

-(UIView *) tableFoodView{
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor whiteColor];
    view.frame = CGRectMake(0, 0, SCREEN_WIDTH, 87);
    UILabel *label1 = [[UILabel alloc] init];
    label1.font = [UIFont systemFontOfSize:12];
    label1.textColor = Text_Gray;
    label1.text = @"已添加";
    [view addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(20);
    }];
    [view addSubview:self.addedLabel];
    [self.addedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(label1.mas_bottom).mas_offset(5);
        make.left.mas_equalTo(label1);
    }];
    
    UILabel *label2 = [[UILabel alloc] init];
    label2.font = [UIFont systemFontOfSize:12];
    label2.textColor = Text_Gray;
    label2.text = @"还可添加";
    self.tipLabel = label2;
    [view addSubview:label2];
    [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.mas_equalTo(SCREEN_WIDTH / 2 + 28);
    }];
    [view addSubview:self.canAddLabel];
    [self.canAddLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(label2.mas_bottom).mas_offset(5);
        make.left.mas_equalTo(label2);
    }];
    
    UIView *line = [UIView new];
    line.backgroundColor = UIColorFromHex(0xF4F4F4);
    [view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.height.mas_equalTo(47);
        make.width.mas_equalTo(2);
    }];
    
    return view;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.showLunch = YES;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = [self tableHeaderView];
    self.tableView.tableFooterView = [self tableFoodView];
    [self.dinnerButton addTarget:self action:@selector(clickDinnerButton) forControlEvents:(UIControlEventTouchUpInside)];
    [self.lunchButton addTarget:self action:@selector(clicklunchButton) forControlEvents:UIControlEventTouchUpInside];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self reloadData];
}

-(void)showAlert:(void (^)(NSError * _Nonnull))errorBlock{
    self.errorBlock = errorBlock;
}

-(void)reloadData{
    [SVProgressHUD showWithStatus:@"正在加载"];
    WEAKSELF
    [DRFoodPairingDataModel familyDietphan:self.showLunch ? @"lunch" : @"dinner" andSuccess:^(DRFamilyFoodPairingModel * _Nonnull model) {
        [SVProgressHUD dismiss];
        STRONGSELF
        strongSelf.model = model;
        [strongSelf.tableView reloadData];
        strongSelf.describeLabel.text = model.hint;
        strongSelf.addedLabel.text = [NSString stringWithFormat:@"%@千卡",model.intake];
        
        if (model.surplus < 0) {
            strongSelf.tipLabel.text = @"已超出";
            strongSelf.canAddLabel.text = [NSString stringWithFormat:@"%ld千卡",(long)-model.surplus];
        }else{
            strongSelf.tipLabel.text = @"还可添加";
            strongSelf.canAddLabel.text = [NSString stringWithFormat:@"%ld千卡",(long)model.surplus];
        }
    } andFail:^(NSError *error) {
        [SVProgressHUD dismiss];
        if (error.code == 400) {
            if (self.errorBlock) {
                self.errorBlock(error);
            }
        }else if (error.code == 500) {
            [SVProgressHUD dismiss];
            WEAKSELF
            if (![DRLoginDataModel isLogin]) {
                return ;
            }
            [DRLoginDataModel setIsLogin:NO];
            [self presentAlertViewWithTitle:@"请重新登录" message:@"" confirmTitle:@"确定" handler:^{
                [weakSelf gotoLogin];
            }];
        }else{
            if ([error.localizedDescription isEqualToString:@"未能读取数据，因为它的格式不正确。"]) {
                [SVProgressHUD showErrorWithStatus:@"本次未能给您匹配出相应数据，请重新请求"];
            }else{
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            }
        }
    }];
}

-(void) setBlackListWithId:(NSString *) foodId dietId:(NSString *) deitId indexPath:(NSIndexPath *) indexPath{
    [DRFoodPairingDataModel setBlackListWithFoodId:foodId andDietId:deitId andSuccess:^(DRFoodMode * _Nonnull model){
        [SVProgressHUD showSuccessWithStatus:@"食物已拉黑"];
        [self reloadData];
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}

-(void) delFoodWithId:(NSString *) foodId indexPath:(NSIndexPath *)indexPath{
    [DRFoodPairingDataModel delFoodWithFoodId:foodId andSuccess:^{
        [self reloadData];
    } andFail:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    }];
}


-(void) clicklunchButton{
    [self.lunchButton setBackgroundColor:There_Green];
    [self.lunchButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.dinnerButton setBackgroundColor:[UIColor whiteColor]];
    [self.dinnerButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    self.showLunch = YES;
    [self reloadData];
}

-(void) clickDinnerButton{
    [self.dinnerButton setBackgroundColor:There_Green];
    [self.dinnerButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [self.lunchButton setBackgroundColor:[UIColor whiteColor]];
    [self.lunchButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    self.showLunch = NO;
    [self reloadData];
}


-(void)didSelectedAddButon:(NSInteger)section{
    dispatch_block_t block = ^ {
        NSString *meal = self.showLunch ? @"lunch": @"dinner";
        NSString *url = [NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/treasureList?ctcp=%@&ctype=2&type=5&token=%@&isBack=1",meal , [DRLoginDataModel getUserToken]];
        NSLog(@"%@",url);
        [self.parentViewController pushWebViewWithUrl:url];
    };
    if (self.model.surplus <= 0) {
        [MMAlertViewConfig globalConfig].itemNormalColor = There_Green;
        MMPopupItem *item1 = MMItemMake(@"取消", MMItemTypeNormal, ^(NSInteger index) {});
        WEAKSELF
        MMPopupItem *item2 = MMItemMake(@"确定", MMItemTypeNormal, ^(NSInteger index) {
            block();
        });
        [self showAlert:@"  " detail:@"已超出总量，是否继续添加" items:@[item1 ,item2]];
    }else{
        block();
    }
    
}


-(void)didSelectedSetEatButton:(NSInteger)section{}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.model.list.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DRFriendsFoodCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRFriendsFoodCell"];
    if (!cell) {
        cell = [DRFriendsFoodCell loadCell];
    }
    DRFoodMode *m = self.model.list[indexPath.row];
    [cell setFoodData:m];
    WEAKSELF
//    MGSwipeButton *button1 = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"lahei_2"] backgroundColor:[UIColor whiteColor] padding:0 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
//        STRONGSELF
//        [strongSelf setBlackListWithId:m._id dietId:m.dietid indexPath:indexPath];
//        return YES;
//    }];
    MGSwipeButton *button2 = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"shanchu"] backgroundColor:[UIColor whiteColor] padding:10 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
        STRONGSELF
        [strongSelf delFoodWithId:m._id indexPath:indexPath];
        return YES;
    }];

//    button1.imageView.contentMode = UIViewContentModeScaleAspectFill;
//    button1.backgroundColor = UIColorFromHex(0xF4F4F4);
    button2.imageView.contentMode = UIViewContentModeScaleAspectFill;
    button2.backgroundColor = UIColorFromHex(0xF4F4F4);
    cell.rightButtons = @[button2];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    DRFoodPairingFooterView *fooderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"DRFoodPairingFooterView"];
    
    if (!fooderView) {
        fooderView = [[DRFoodPairingFooterView alloc] initWithReuseIdentifier:@"DRFoodPairingFooterView"];
        fooderView.delegate = self;
    }

    fooderView.section = section;
    fooderView.delegate = self;
    [fooderView.setEatButton setHidden:YES];
    [fooderView.addButton setTitle:self.showLunch ? @"添加午餐" :@"添加晚餐" forState:(UIControlStateNormal)];
    
    
    return fooderView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 60;
}

@end
